<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增销售订单</title>
    <script type="text/javascript">
      var authLoginWin;
      var roleDiscount = <%=session[:role].discount%>;
      var oriSaleTypeDiscount = null;
      var oriSaleTypeId = null;
      var curSaleTypeDiscount = null;
      Ext.onReady(function(){
        Ext.Loader.setConfig({
          enabled: true
        });

        //此角色的最大折扣权限。
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });

        var authentication = Ext.create('Ext.form.field.Hidden', {
          name: 'authentication',
          value: 0
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });

        //出库说明
        var deliveryDesc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '出库说明',
          name: 'delivery_desc',
          anchor: '100%'
        });

        //所有客户
        var toCustomer = Ext.create('Ext.form.ComboBox', {
          fieldLabel: '到客户',
          store: customerAllInfoStore,
          allowBlank: false,
          blankText: "客户必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'customer_id',
          loadingText: '搜索中...',
          minChars: 0,
          anchor: '100%',
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:60px">{number}</div><div style="float:left;width:150px">|{name:ellipsis(12)}</div>| {phone:ellipsis(28)}';
            }
          },
          pageSize: 10
        });

        toCustomer.on('select', function(combo, record, index) {
          if (record[0].get('linkman') === "" ){
            linkman.setValue(record[0].get('name'));
          }else{
            linkman.setValue(record[0].get('linkman'));
          }
          phone.setValue(record[0].get('phone'));
          deliveryAddress.setValue(record[0].get('address'));
        });

        var addCustomerButton = Ext.create('Ext.Button', {
          text: '添加客户',
          iconCls: 'addItem',
          scale: 'small',
          handler: onAddCustomerButtonClick
        });

        function onAddCustomerButtonClick(){
          newCustomerWin = Ext.create('Ext.window.Window', {
            layout: 'fit',
            width:618,
            height:300,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            //modal: true,
            title: '添加客户',
            autoLoad: {
              url: "/customer/newCustomer",
              scripts: true
            }
          });
          newCustomerWin.resizable = false;
          newCustomerWin.show();
        }

        //销售类型
        var saleType = Ext.create('Ext.form.ComboBox', {
          store: saleTypeStore,
          fieldLabel: '销售类型',
          allowBlank: false,
          blankText: "销售类型必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name:'sale_type_id',

          loadingText: '搜索中...',
          anchor: '95%',
          editable:false,
          minChars: 0,
          triggerAction:"all"
        });

        saleType.on('select', function(combo, record, index) {
          //这里要判断有一种情况是要从新取得价格，给grid中的单价设置上价格，然后用resetPrice再从新设置一下。
          //oriSaleTypeDiscount != null代表了不是第一次选择。oriSaleTypeId != record[0].get('id')代表进行了不同的选择。
          if (oriSaleTypeDiscount != null && oriSaleTypeId != record[0].get('id')){
            //这里一但销售类型变化 ，都要从新取一次价格，然后从新变更价格
            var saleTypeId = record[0].get('id');
            var productIdStr = getFieldStringFromGridStore(saleOrderDetailDS,'product_id');
            Ext.Ajax.request({
              url : '/product/getPricesBySTIdPIds',
              success : function (result, request) {
                //先把标志位置清空
                clearFieldValueForGridStore(saleOrderDetailDS,'sale_type_price',-1);
                if (Ext.JSON.decode(result.responseText).root.length != 0){
                  for (var i = 0 ; i < Ext.JSON.decode(result.responseText).root.length;i++ ){
                    var productPrice = Ext.JSON.decode(result.responseText).root[i];
                    var saleOrderDetailRecords = saleOrderDetailDS.find('product_id',productPrice.product_id);
                    if (saleOrderDetailRecords.length > 0){
                      var saleOrderDetailRecord = saleOrderDetailRecords.get(0);
                      //sale_type_price，现在是替换基准价。
                      saleOrderDetailRecord.set('sale_type_price',productPrice.unit_price);
                    }
                  }
                }

                curSaleTypeDiscount = record[0].get('discount');
                resetPrice();
              },
              failure : function (result, request){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "通讯失败，请从新操作",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.WARNING
                });
              },
              method : 'POST',
              params : {
                sale_type_id : saleTypeId,
                product_ids : productIdStr,
                authenticity_token: authToken.getValue()
              }
            });
          }

          if (curSaleTypeDiscount == null){
            curSaleTypeDiscount = record[0].get('discount');
          }
          oriSaleTypeDiscount = curSaleTypeDiscount;
          oriSaleTypeId = record[0].get('id');
        });

        //销售策略

        var salesStrategy = Ext.create('Ext.form.ComboBox', {
          store: salesStrategyStore,
          fieldLabel: '销售策略',
          allowBlank: false,
          blankText: "销售策略必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'sales_strategy_id',
          loadingText: '搜索中...',
          anchor: '95%',
          editable:false,
          minChars: 0,
          triggerAction:"all"
        });

        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '发货日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "发货日期必须选择",
          emptyText: '发货日期...',
          anchor: '95%'
        });

        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false,
          anchor: '95%'
        });

        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false,
          anchor: '95%'
        });

        //默认折扣
        var defaultDiscount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '默认折扣',
          name:"default_discount",
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          maxValue: 2,
          mouseWheelEnabled:true,
          step: 0.01,
          anchor: '95%',
          value:0.25
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
          fieldLabel: '税率(%)',
          name:"tax_rate",
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          minValue:0,
          maxValue: 100,
          anchor: '95%',
          value:17
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '97%'
        });

        //销售员
        var sales = Ext.create('Ext.form.ComboBox', {
          store: employeeStore,
          fieldLabel: '销售员',
          allowBlank: false,
          blankText: "销售员必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'sales_id',
          editable:false,
          loadingText: '搜索中...',
          anchor: '95%',
          minChars: 0
        });

        //业绩部门
        var sellDept = Ext.create('Ext.form.ComboBox', {
          store: departmentStore,
          fieldLabel: '业绩部门',
          allowBlank: false,
          blankText: "业绩部门必须选择",
          valueField: 'department_id',
          displayField: 'name',
          name: 'sell_dept_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          editable:false,
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          readOnly:false,
          minChars: 0
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });

        //首付金额
        var recAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '首付金额',
          name:"rec_amount",
          allowBlank: true,
          allowDecimals: true,
          minValue: 0,
          minValue:0,
          anchor: '90%'
        });

        var paymentType = Ext.create('Ext.form.ComboBox', {
          fieldLabel: '付款方式',
          store: paymentTypeStore,
          valueField:'text',
          displayField:'text',
          mode: 'local',
          name:'payment_type',
          emptyText:'请选择付款方式...',
          allowBlank: true,
          editable:false,
          anchor: '95%'
        });

        //付款备注
        var paymentDesc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '付款备注',
          name: 'payment_desc',
          anchor: '95%'
        });
        //--------------------------------------------------------------------------
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productAllInfoStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';              
            }
          },
          pageSize: 10
        });

        //select( Ext.form.field.Picker field, Mixed value, Object options )
        productCBB.on('select', function(field, record, options) {
          var records = saleOrderDetailGrid.getSelectionModel().getSelection();
          var saleOrderItemRecord = records[0];
          if (!saleOrderItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(saleOrderDetailDS,record[0].get('id'),saleOrderItemRecord.id)){
            //删除当前记录
            saleOrderDetailDS.remove(saleOrderItemRecord);
          }else{
            if (saleOrderItemRecord.get('product_id') != record[0].get('id')){
              saleOrderItemRecord.set('number',record[0].get('number'));
              saleOrderItemRecord.set('spec',record[0].get('spec'));
              saleOrderItemRecord.set('unit',record[0].get('unit'));
              saleOrderItemRecord.set('quantity',1);
              saleOrderItemRecord.set('ori_unit_price',record[0].get('unit_price'));
              saleOrderItemRecord.set('discount',defaultDiscount.getValue());
              saleOrderItemRecord.set('product_id',record[0].get('id'));
              //判断套装
              saleOrderItemRecord.set('is_suit',record[0].get('is_suit'));
              //单价要特别拿出来处理,如果有销售类型的价格则使用，如果没有就使用销售类型的通用折扣。
              Ext.Ajax.request({
                url : '/product/getPricesBySTIdPIds',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).root.length != 0){
                    var productPrice = Ext.JSON.decode(result.responseText).root[0];
                    saleOrderItemRecord.set('unit_price',productPrice.unit_price);
                  }else{
                    saleOrderItemRecord.set('unit_price',Math.round(1000*record[0].get('unit_price')* curSaleTypeDiscount)/1000);
                  }
                  saleOrderItemRecord.set('amount',saleOrderItemRecord.get('unit_price')*saleOrderItemRecord.get('discount'));
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                },
                method : 'POST',
                params : {
                  sale_type_id : oriSaleTypeId,//oriSaleTypeId在这儿就是指上次选择的值。
                  product_ids : record[0].get('id'),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
          //从新计算得出总价。
          getSumAmount();
        });

        //销售订单列表Grid Store
        //新增销售订单详细信息Model
        Ext.define('SaleOrderDetailAddModel', {
          extend : 'Ext.data.Model',
          fields : [{name: 'id'},
            {name: 'number'},
            {name: 'unit'},
            {name: 'spec'},
            {name: 'name'},
            {name: 'description'},
            {name: 'quantity',type: 'int'},
            {name: 'discount',type: 'float'},
            {name: 'amount',type: 'float'},
            {name: 'unit_price',type: 'float'},
            {name: 'ori_unit_price',type: 'float'},
            {name: 'product_id'},
            {name: 'product_name'},
            {name: 'is_suit'},
            {name: 'sale_type_price'}//有此值就要直接使用此值，不能使用销售类型带的折扣。
          ]
        });


        var saleOrderDetailDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'SaleOrderDetailAddModel',
          proxy : {
            type : 'ajax',
            //url : '/sale_order/getSaleOrderDetailsBalanceById',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });

        //生成要订单的产品的Grid
        var saleOrderDetailGrid = Ext.create('Ext.grid.Panel', {
          store: saleOrderDetailDS,
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 80
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 40
            },{
              header: '数量',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              align: 'right',
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 70
            },{
              header: '折扣',
              dataIndex: 'discount',
              renderer: Ext.util.Format.numberRenderer('0,000.000000'),
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: true,
                minValue: 0,
                decimalPrecision:6,
                maxValue: 2,
                mouseWheelEnabled:true,
                step: 0.01
              }),
              width: 70
            },{
              header: '金额',
              dataIndex: 'amount',
              align: 'right',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: true,
                minValue: 0
              }),
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 70
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 60,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '100%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          /*selModel: {
            selType: 'cellmodel'
          },*/
          plugins: [cellEditing],
          width: 1050,
          height: 265,
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                if (saleType.getValue() != null){
                  var record =  Ext.create('SaleOrderDetailAddModel', {product_name: '请选择产品'});
                  saleOrderDetailDS.insert(0, record);
                }else{
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "请先选择“销售类型”！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                }
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = saleOrderDetailGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                saleOrderDetailDS.remove(records);
                getSumAmount();
              }
            }]
        });

        //授信按钮
        var authButton = Ext.create('Ext.Button', {
          text: '授信',
          tooltip: '权限授信。',
          iconCls: 'icon-save',
          handler: function(){
            authLoginWin = Ext.create('Ext.window.Window', {
              layout: 'fit',
              width: 217,
              height: 138,
              closeAction: 'destroy',
              plain: true,
              modal: true,
              constrain:true,
              //modal: true,
              title: '授信登录',
              autoLoad: {
                url: "/employee/authLogin",
                scripts: true
              }
            });
            authLoginWin.on("destroy",function(){
            });
            authLoginWin.resizable = false;
            authLoginWin.show();
          }
        });

        //提交按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '保存并提交销售订单。',
          iconCls: 'icon-save',
          handler: function(){
            //.setDisabled(true);
            //如果输入了首付金额，就要填写付款方式
            if (recAmount.getValue() != null && recAmount.getValue() != 0){
              paymentType.allowBlank = false;
            }

            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
              return;
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
              return;
            }

            if (saleOrderFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(saleOrderDetailDS,rejectKeyArray);
              if (saleOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (saleOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //首付不能大于总金额
              if (recAmount.getValue() != null && recAmount.getValue() != 0){
                if (sumAmount.getValue() < recAmount.getValue()){
                  Ext.MessageBox.alert("提示","付款金额大于商品总金额！");
                  return;
                }
              }
              //在提交前检查折扣有没有小于系统规定折扣的。
              authentication.setValue(0);
              var records = saleOrderDetailDS.getRange(0,saleOrderDetailDS.getCount());
              var isUnsafeDiscountSubmit = false;
              for(var i = 0; i< records.length ;i++){
                var record = records[i];
                var discount = record.get('discount');
                if (parseFloat(discount) < parseFloat(roleDiscount)){
                  isUnsafeDiscountSubmit = true;
                  break;
                }
              }

              if (isUnsafeDiscountSubmit == true){
                Ext.MessageBox.confirm("提示","您输入的产品折扣中有小于系统要求"+roleDiscount+"折的，请点击'否'从新检查后再提交，或点击'是'提交后将进入折扣授信审批。",function(btn){
                  if(btn=="yes"){
                    authentication.setValue(1);
                    submitButton.disable();
                    var allJsonStr = saleOrderFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

                    Ext.Ajax.request({
                      url : '/sale_order/create',
                      success : function (result, request) {
                        if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                          Ext.MessageBox.show({
                            title: '消息',
                            msg: "新增销售订单，操作成功！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                          });
                        }
                        else {
                          Ext.MessageBox.show({
                            title: '消息',
                            msg: Ext.JSON.decode(result.responseText).info,
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.WARNING
                          });
                        }
                        newSaleOrderWin.destroy();
                      },
                      failure : function (result, request){
                        Ext.MessageBox.show({
                          title: '消息',
                          msg: "通讯失败，请从新操作",
                          buttons: Ext.MessageBox.OK,
                          icon: Ext.MessageBox.WARNING
                        });
                        newSaleOrderWin.destroy();
                      },
                      method : 'POST',
                      params : {
                        data : Ext.JSON.encode(allJsonStr),
                        authenticity_token: authToken.getValue()
                      }
                    });
                  }else{
                    return;
                  }
                });
              }else{
                submitButton.disable();
                var allJsonStr = saleOrderFormPanel.getForm().getValues();
                allJsonStr = Ext.JSON.encode(allJsonStr);
                allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

                Ext.Ajax.request({
                  url : '/sale_order/create',
                  success : function (result, request) {
                    if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                      Ext.MessageBox.show({
                        title: '消息',
                        msg: "新增销售订单，操作成功！",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.INFO
                      });
                    }
                    else {
                      Ext.MessageBox.show({
                        title: '消息',
                        msg: Ext.JSON.decode(result.responseText).info,
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.WARNING
                      });
                    }
                    newSaleOrderWin.destroy();
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                    newSaleOrderWin.destroy();
                  },
                  method : 'POST',
                  params : {
                    data : Ext.JSON.encode(allJsonStr),
                    authenticity_token: authToken.getValue()
                  }
                });
              }
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '暂存',
          tooltip: '暂时保存销售订单。',
          iconCls: 'temp-save',
          handler: function(){

            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }

            //首先把临时变量设置为1
            temporary.setValue(1);

            //如果输入了首付金额，就要填写付款方式
            if (recAmount.getValue() != null && recAmount.getValue() != 0){
              paymentType.allowBlank = false;
            }

            if (saleOrderFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(saleOrderDetailDS,rejectKeyArray);
              if (saleOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              //没有添加产品，则提示
              if (saleOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //首付不能大于总金额
              if (recAmount.getValue() != null && recAmount.getValue() != 0){
                if (sumAmount.getValue() < recAmount.getValue()){
                  Ext.MessageBox.alert("提示","付款金额大于商品总金额！");
                  return;
                }
              }

              this.disable();
              var allJsonStr = saleOrderFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/sale_order/create',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "暂存销售订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  newSaleOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newSaleOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });


        //关闭按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newSaleOrderWin.destroy();
          }
        });

        //采购申请的FormPanel
        var saleOrderFormPanel = Ext.create('Ext.form.Panel', {
          //baseCls: 'x-plain',
          //renderTo: 'new_sale_order',
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '1050',
          frame : true,
          url: '/sale_order/create',
          method: 'GET',
          items: [{
              layout: 'column',
              xtype: 'container',
              anchor: '100%',
              items: [{
                  columnWidth: .5,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toCustomer]
                }, {
                  columnWidth: .1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [addCustomerButton]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [defaultDiscount]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [contractNumber]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              anchor: '100%',
              items: [{
                  columnWidth: .25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .35,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [taxRate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .6,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [deliveryAddress]
                },{
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [saleType]
                },{
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sales]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .6,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                },{
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [salesStrategy]
                },{
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sellDept]
                }]
            },deliveryDesc,{
              layout: 'column',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [saleOrderDetailGrid]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 0.2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumAmount]
                },{
                  columnWidth: 0.2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [recAmount]
                },{
                  columnWidth: 0.2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [paymentType]
                },{
                  columnWidth: 0.4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [paymentDesc]
                }]
            },temporary,authentication],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        saleOrderFormPanel.render('new_sale_order');

        saleOrderDetailGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options){
          //判断一下用户给产品设置的权限是不是小于他固有权限的折扣。
          roleDiscount = parseFloat(roleDiscount);
          /*if (obj.field=="discount" && obj.record.get('discount') < roleDiscount){
            obj.record.set('discount',roleDiscount);
          }*/
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          //根据当前的销售类型，来计算销售价或折扣
          if(obj.field=="quantity" || obj.field=="unit_price" || obj.field=="discount"){
            if(obj.record.get('quantity')>0 && obj.record.get('unit_price') >0){
              obj.record.set('amount',Math.round(obj.record.get('quantity')*10000000*obj.record.get('unit_price')*obj.record.get('discount'))/10000000);
            }else{
              obj.record.set('amount',0);
            }
          }

          //如果有人提前输入了最终价格，那可以自动算出折扣。
          if(obj.field=="amount"){
            if(obj.record.get('quantity')>0 && obj.record.get('unit_price') >0){
              obj.record.set('discount',Math.round(obj.record.get('amount')/(obj.record.get('quantity')*1000*obj.record.get('unit_price')/1000)*1000000)/1000000);
            }else{
              obj.record.set('amount',0);
            }
          }

          getSumAmount();
        }

        function getSumAmount(){
          sumAmount.setValue(0);
          var records = saleOrderDetailDS.getRange(0,saleOrderDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var amount = record.get('amount');
            if (amount === undefined){
              amount = 0;
            }
            sumAmount.setValue(sumAmount.getValue()+Number(amount));
          }
        }

        //当切换销售类型时用它来从新计算价格
        function resetPrice(){
          var records = saleOrderDetailDS.getRange(0,saleOrderDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            //如果没有类型价，就设置原始价*折扣，如果有，直接用类型价。
            if (record.get('sale_type_price') == -1){
              var unitPirce = Math.round(1000*record.get('ori_unit_price') * curSaleTypeDiscount)/1000;
            }else{
              var unitPirce = record.get('sale_type_price');
            }
            record.set('unit_price',unitPirce);
            record.set('amount',Math.round(10000*record.get('unit_price')*record.get('quantity')*record.get('discount'))/10000);
          }
          getSumAmount();
        }
      })
    </script>
  </head>
  <body>
    <div id="new_sale_order"></div>
  </body>
</html>